package com.holly.unit.deform.designer.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Map;

/**
 * 类描述: 脚本工具类
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/8/4 15:14
 */
@Slf4j
public class ScriptUtil {

    private static ScriptEngine engine =  null;

    private ScriptUtil() {
        throw new UnsupportedOperationException("ScriptUtil类无法实例化");
    }

    public static ScriptEngine getScriptEngine() {
        if(engine == null) {

            ScriptEngineManager manager = new ScriptEngineManager();
            engine =  manager.getEngineByName("javascript");
            try {
                engine.eval("function func(script,model,data){" +
                        " var Fn = new Function('$', 'data', script) ;" +
                        "  return  Fn(model , data);" +
                        "}");
            } catch (ScriptException e) {
                e.printStackTrace();
            }

        }
        return engine;
    }

    public static Object getScirptValue(String script , Map<String, Object> value) {
        if(StrUtil.isBlank(script)) {
            return false ;
        }
        if(script.contains("return")) {
            script = "{" + script + "}";
        } else {
            script = "return (" + script + ")" ;
        }
        ScriptEngine engine = getScriptEngine();
        try{

            if (engine instanceof Invocable) {
                Invocable in = (Invocable) engine;
                Object ret = in.invokeFunction("func",script,value) ;
                System.out.println("script:" + script + " , ret: " + ret);
                return ret ;
            }
        }catch(Exception e){
            log.error("脚本处理发生错误.  script:[{}]" ,   script);
            log.error(e.toString());

        }
        return null;
    }
}
